require './Api.rb'
require 'sqlite3'
class Trader
    def initialize
        @api = Api::Bter.new('209BA9B0-5DBA-4787-92DF-E24EA8C9231A','cc1d4f861bb29ae1dd89244ad446e4636ead5817b54c4b68a5eb65395dcf6486')
        #@market_info=@api.marketinfo()['pairs']
        @market_list=@api.marketlist()['data']
        @tickers=@api.tikers
        @db = SQLite3::Database.new("data.db")
        @db.results_as_hash = true
        @db.execute("CREATE TABLE IF NOT EXISTS balance (coin char(5),balance float);")
        @db.execute("CREATE TABLE IF NOT EXISTS trade_log (from_coin char(5),to_coin char(5),amount float,rate float,timeline int);")
    end

    def weight(p1,p2)
        weight=0
        history = @api.trade_history(p1,p2)
        if history == nil then
            return nil
        end
        #puts history
        history_data = history['data']
        if history_data[history_data.length-1]['rate']>history_data[0]['rate'] then
            weight+=1
        end
        rate = 0.1
        first = history_data[0]['rate']
        history_data.each do |x|
            if x['rate'] > first then
                rate += 0.1
            end
            if x['type'] == 'buy' then
                rate += 0.1
            end
            first = x['rate']
        end
        rate = rate/history_data.length
        ticker = @tickers["#{p1}_#{p2}"]
        if ticker['high24hr'] != ticker['last'] then
            rate += (ticker['last']-ticker['low24hr']) / (ticker['high24hr']-ticker['last'])
        end
        weight * rate
    end

    def get_my_balance
        result = @db.execute('select * from balance')
    end

    def maybe_trade
        results = {}
        balance = get_my_balance
        balance.each do|v|
            @market_list.each do |y|
                ys = y['pair'].split('_')
                if ys[0] == v['coin'] then
                    results[y['pair']] = {
                        :balance => v['balance'],
                        :weight => weight(ys[0],ys[1])
                    }
                end
            end
        end
        results
    end

    def buy(from,to,rate,amount)
        @db.execute("selete from balance")
        @db.execute("insert into balance (coin,balance) values ('#{to}',#{rate*amount})")
        @db.execute("insert into trade_log (from_coin,to_coin,rate,amount,timeline) values ('#{from}','#{to}',#{rate},#{amount},#{Time.new().to_i})")
    end

    def trader
        maybe = maybe_trade
        pair = nil
        weight = 0
        maybe.each_key do |key|
            if weight < maybe[key]['weight'] then
                weight = maybe[key]['weight']
                pair = key
            end
        end
        if pair == nil then
            return nil
        end
        ticker = @tickers[pair]
    end
end


t = Trader.new
puts t.trader
#puts t.weight('btc','ltc')